//
//  CYViewController.m
//  悦享
//
//  Created by dllo on 16/3/17.
//  Copyright © 2016年 张洪国. All rights reserved.
//

#import "CYViewController.h"
#import <MJRefresh.h>

@interface CYViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>


@property (nonatomic, retain) UICollectionView *bigCollectionView;   /**< 创建底部大的collectionView */

@property (nonatomic, retain) UICollectionView *guideCollection;   /**< 创建上面的小的collectionView */
@property (nonatomic, retain) NSArray *titleArr;   /**< 小collectionView上的汉字 */

@property (nonatomic, assign) NSInteger count;   /**< 记录 */

@property (nonatomic, retain) UIButton *refreshButton;   /**< 手动点击刷新按钮 */

@property (nonatomic, assign) BOOL refreshStop;

@property (nonatomic, retain) UISegmentedControl *segment;



@end

@implementation CYViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationController.navigationBar.translucent = NO;
    
    self.navigationController.navigationBar.barStyle = UIStatusBarStyleLightContent;

    [self createSegment];
    [self segAction:_segment];
//    [self createGuideCollectionView];
//    [self creataBigCollectionView];
//    [self createrefreshButton];
    
    self.titleArr = [NSArray arrayWithObjects:@"推荐", @"视频", @"图片", @"段子", @"精华", nil];
    
    self.count = 0;
    
    _refreshStop = NO;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshStop:) name:@"refresh" object:nil];
    
}

#pragma mark - navigation
- (void)createSegment {
  
    // 创建segment
    self.segment = [[UISegmentedControl alloc] initWithItems:@[@"段子", @"音乐"]];
    self.navigationItem.titleView = _segment;
    _segment.tintColor = [UIColor whiteColor];
    _segment.selectedSegmentIndex = 0;
    _segment.frame = CGRectMake(0, 0, 200, 30);
    [_segment addTarget:self action:@selector(segAction:) forControlEvents:UIControlEventValueChanged];
    
    // 登录
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-yonghu"] style:UIBarButtonItemStylePlain target:self action:@selector(landAction:)];
    
    self.navigationItem.leftBarButtonItem = leftItem;
    
}

#pragma mark - 刷新button初始化

- (void)createrefreshButton {
    
    self.refreshButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_refreshButton setImage:[UIImage imageNamed:@"iconfont-shuaxin"] forState:UIControlStateNormal];
    _refreshButton.frame = CGRectMake(SREEN_WIDTH - 50, SREEN_HEIGHT - 200, 40, 40);
    
    [_refreshButton addTarget:self action:@selector(refreshButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_refreshButton];
    
    
    
}

#pragma mark - 创建音乐界面

- (void)createMusic {
    
    
    
    
}

#pragma mark - 创建大的collectionView
- (void)creataBigCollectionView {
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    
    layout.itemSize = CGSizeMake(SREEN_WIDTH, SREEN_HEIGHT - 40);
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 0;
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    
    self.bigCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 40, SREEN_WIDTH, SREEN_HEIGHT - 40) collectionViewLayout:layout];
    [self.view addSubview:_bigCollectionView];
    
    _bigCollectionView.bounces = NO;
    
    _bigCollectionView.pagingEnabled = YES;
    
    _bigCollectionView.delegate = self;
    _bigCollectionView.dataSource = self;
    
    [_bigCollectionView registerClass:[HS_BigCollectionViewCell class] forCellWithReuseIdentifier:@"HS_BigCollectionViewCell"];
    
    [_bigCollectionView registerClass:[HS_PhotoCollectionViewCell class] forCellWithReuseIdentifier:@"HS_PhotoCollectionViewCell"];
}


#pragma mark - 创建小的collectionView
- (void)createGuideCollectionView {
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    // 滑动方向
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    // item 大小
    layout.itemSize = CGSizeMake((SREEN_WIDTH - 70) / 5, 40);
    // 最小行间距
    layout.minimumLineSpacing = 15;
    // 最小列间距
    layout.minimumInteritemSpacing = 0;
    // 四周间距
    layout.sectionInset = UIEdgeInsetsMake(0, 5, 0, 5);
    
    // 创建titleCollectionView
    self.guideCollection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SREEN_WIDTH, 40) collectionViewLayout:layout];
    // 将titleCollection添加到navigationbar上
    [self.view addSubview:_guideCollection];
    // 设置代理人
    _guideCollection.delegate = self;
    _guideCollection.dataSource = self;
    
    _guideCollection.backgroundColor = [UIColor whiteColor];
    
    // 重用池
    [_guideCollection registerClass:[GuideCollectionViewCell class] forCellWithReuseIdentifier:@"GuideCollectionViewCell"];
    

    
}

#pragma mark - UICollectionView 协议方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return _titleArr.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (_guideCollection == collectionView) {
        GuideCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"GuideCollectionViewCell" forIndexPath:indexPath];
        
        cell.titleLabel.text = _titleArr[indexPath.row];
        cell.titleLabel.tag = 1000 + indexPath.row;
        if (indexPath.row == 0) {
            cell.titleLabel.textColor = [UIColor redColor];
            cell.titleLabel.font = [UIFont systemFontOfSize:20];
        }
        return cell;
        
    }else{
        
        switch (indexPath.row) {
            case 0:
            {
                HS_BigCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HS_BigCollectionViewCell" forIndexPath:indexPath];
                
                [cell.collectionView.mj_header beginRefreshing];
                
                cell.http = @"http://ic.snssdk.com/neihan/stream/mix/v1/?content_type=-101&iid=3884110173&idfa=CC297599-F80A-4C4F-8DFC-4F65C16D631A&version_code=5.0.1&device_type=iPhone%204S&aid=7&os_version=9.2&screen_width=640&vid=9E9DB803-0CCD-4056-A7B5-76B872D127B8&device_id=12502110594&os_api=18&app_name=joke_essay&device_platform=iphone&ac=WIFI&openudid=0eba183e415ee4a9dd1e8dd7dd41fa299bbdd311&channel=App%20Store&city=%E8%BE%BD%E5%AE%81%E7%9C%81&content_type=-101&count=30&essence=1&latitude=38.8825674484985&longitude=121.5393482552343&message_cursor=0&min_time=1458205760&mpic=1";
                return cell;
                
            }break;
            case 1:{
                HS_BigCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HS_BigCollectionViewCell" forIndexPath:indexPath];
                
                [cell.collectionView.mj_header beginRefreshing];
                
                cell.http = @"http://ic.snssdk.com/neihan/stream/mix/v1/?content_type=-104&iid=3884055677&idfa=C142307D-73E9-409F-88B5-2F7B28503941&version_code=5.0.1&device_type=iPhone%205C&aid=7&os_version=8.4.1&screen_width=640&vid=49B27B78-9F34-4233-BB67-97879EA7A3F6&device_id=10249917773&os_api=18&app_name=joke_essay&device_platform=iphone&ac=WIFI&openudid=3398741dc71d9d588d52c19cecb7113caf3c7a13&channel=App%20Store&content_type=-104&count=30&essence=1&message_cursor=0&min_time=1458117733&mpic=1";
                return cell;
                
            }break;
            case 2:{
                HS_BigCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HS_BigCollectionViewCell" forIndexPath:indexPath];
                
                [cell.collectionView.mj_header beginRefreshing];
                
                cell.http = @"http://ic.snssdk.com/neihan/stream/mix/v1/?content_type=-103&iid=3884055677&idfa=C142307D-73E9-409F-88B5-2F7B28503941&version_code=5.0.1&device_type=iPhone%205C&aid=7&os_version=8.4.1&screen_width=640&vid=49B27B78-9F34-4233-BB67-97879EA7A3F6&device_id=10249917773&os_api=18&app_name=joke_essay&device_platform=iphone&ac=WIFI&openudid=3398741dc71d9d588d52c19cecb7113caf3c7a13&channel=App%20Store&content_type=-103&count=30&essence=1&message_cursor=0&min_time=1458120103&mpic=1";
                
                return cell;
            }break;
            case 3:{
                
                HS_BigCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HS_BigCollectionViewCell" forIndexPath:indexPath];
                
                [cell.collectionView.mj_header beginRefreshing];
                
                cell.http = @"http://ic.snssdk.com/neihan/stream/mix/v1/?content_type=-102&iid=3884055677&idfa=C142307D-73E9-409F-88B5-2F7B28503941&version_code=5.0.1&device_type=iPhone%205C&aid=7&os_version=8.4.1&screen_width=640&vid=49B27B78-9F34-4233-BB67-97879EA7A3F6&device_id=10249917773&os_api=18&app_name=joke_essay&device_platform=iphone&ac=WIFI&openudid=3398741dc71d9d588d52c19cecb7113caf3c7a13&channel=App%20Store&content_type=-102&count=30&essence=1&message_cursor=0&min_time=1458120670&mpic=1";
                return cell;
            }break;
                
            default:
                break;
        }


        HS_PhotoCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HS_PhotoCollectionViewCell" forIndexPath:indexPath];
        
        cell.http = @"http://toutiao.com/ma/?media_id=5234320301&count=10&max_behot_time=0&csrfmiddlewaretoken=undefined&_=1458811329171";
        
        return cell;
        
    }
    
}


// collectionView点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (_guideCollection == collectionView) {
        
        GuideCollectionViewCell *cell = (GuideCollectionViewCell *)[_guideCollection cellForItemAtIndexPath:indexPath];
        // 第一次点击时改变推荐字体与大小
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            
            UILabel *lableIndexOne = [_guideCollection viewWithTag:1000];
            lableIndexOne.textColor = [UIColor blackColor];
            lableIndexOne.font = [UIFont systemFontOfSize:17];
            
        });
        
        UILabel *lable = [_guideCollection viewWithTag:1000 + _count];
        lable.textColor = [UIColor blackColor];
        lable.font = [UIFont systemFontOfSize:17];
        
        cell.titleLabel.textColor = [UIColor redColor];
        cell.titleLabel.font = [UIFont systemFontOfSize:20];
        
        [_bigCollectionView setContentOffset:CGPointMake(SREEN_WIDTH * indexPath.row, 0) animated:NO];

    }
}
// 点击之后的方法
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (_guideCollection == collectionView) {
        
        UILabel *titleLable = [_guideCollection viewWithTag:1000 + indexPath.row];
        titleLable.textColor = [UIColor blackColor];
        titleLable.font = [UIFont systemFontOfSize:17];
 
    }
    
}

#pragma mark - 登录点击方法
- (void)landAction:(UIBarButtonItem *)item {
    
    LandViewController *landVC = [[LandViewController alloc] init];
    
    [self.navigationController pushViewController:landVC animated:YES];
    
}


// collectionView将要停止运动
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    self.count = _bigCollectionView.contentOffset.x / SREEN_WIDTH;
    UILabel *lable = [_guideCollection viewWithTag:1000 + _count];
    lable.font = [UIFont systemFontOfSize:20];
    lable.textColor = [UIColor redColor];
    
    UILabel *label1 = [_guideCollection viewWithTag:1000 + _count - 1];
    label1.font = [UIFont systemFontOfSize:17];
    label1.textColor = [UIColor blackColor];
    
    UILabel *label2 = [_guideCollection viewWithTag:1000 + _count + 1];
    label2.font = [UIFont systemFontOfSize:17];
    label2.textColor = [UIColor blackColor];

    // 通知当更换cell的时候视频暂停
    [[NSNotificationCenter defaultCenter] postNotificationName:@"playerPause" object:nil];
    
}

#pragma mark - segment点击方法
- (void)segAction:(UISegmentedControl *)seg {
    
    if (seg.selectedSegmentIndex == 0) {
        
        [self creataBigCollectionView];
        [self createGuideCollectionView];
        [self createrefreshButton];
        
    }else{
        
        [_bigCollectionView removeFromSuperview];
        [_guideCollection removeFromSuperview];
        [_refreshButton removeFromSuperview];
    }
    
}


#pragma mark - 刷新按钮点击方法 

- (void)refreshButtonAction:(UIButton *)refresh {
    
    // CALayer动画
    // Core Animation
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    // 旋转的起始值
    animation.fromValue = [NSNumber numberWithFloat:0];
    // 旋转的结束值
    // π是180° 2π是360°
    animation.toValue = [NSNumber numberWithFloat:M_PI * 2];
    // 重复次数
    animation.repeatCount = NSIntegerMax;
    // 时间
    animation.duration = 1;
    // 是否自动回到原来位置
    animation.autoreverses = NO;
    // 是否按照结束位置继续旋转
    animation.cumulative = YES;
    
    [self.refreshButton.layer addAnimation:animation forKey:@"标记"];
    
    [_bigCollectionView reloadData];
    
    if (!_refreshStop) {
        // 继续
        // 找到时间偏移量
        CFTimeInterval stopTime = self.refreshButton.layer.timeOffset;
        // 速度设置为1
        self.refreshButton.layer.speed = 1;
        
        // 把beginTime重置
        self.refreshButton.layer.beginTime = 0;
        self.refreshButton.layer.timeOffset = 0;
        // 设置开始的时间
        self.refreshButton.layer.beginTime = [self.refreshButton.layer convertTime:CACurrentMediaTime() fromLayer:nil] - stopTime;
        _refreshStop = YES;
    }
    
    NSLog(@"刷新");
    
}

#pragma mark - 通知停止刷新旋转
- (void)refreshStop:(NSNotificationCenter *)refresh {
    
    if (_refreshStop) {
        
        // 暂停
        CFTimeInterval stopTime = [self.refreshButton.layer convertTime:CACurrentMediaTime() fromLayer:nil];
        // 设置动画速度
        self.refreshButton.layer.speed = 0;
        // 保存时间的偏移量
        self.refreshButton.layer.timeOffset = stopTime;
        
        _refreshStop = NO;
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
